package com.example.firstjavamqtt.service.base.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.firstjavamqtt.common.excepiton.GlobalException;
import com.example.firstjavamqtt.common.result.ResultCodeEnum;
import com.example.firstjavamqtt.mapper.UserMapper;
import com.example.firstjavamqtt.model.base.User;
import com.example.firstjavamqtt.service.base.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void register(User user) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        user.setSalt(salt);
        String password = new Md5Hash(user.getPassword(), salt, 1024).toHex(); //生成的密文
        user.setPassword(password);
        if (getByUsername(user.getUsername()) != null) {
            throw new GlobalException(ResultCodeEnum.REPEAT_REGISTER);
        }
        baseMapper.insert(user);
    }

    @Override
    public User getByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public void login(User user) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            SecurityUtils.getSubject().login(token);
        }  catch (UnknownAccountException e) {
            throw new GlobalException(ResultCodeEnum.ERROR_USERNAME);
        } catch (IncorrectCredentialsException e) {
            throw new GlobalException(ResultCodeEnum.ERROR_PASSWORD);
        } catch (Exception e) {
            throw new GlobalException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    @Override
    public Page<User> getAll(int pageNum, int limit) {
        Page<User> userPage = new Page<>(pageNum, limit);
        return baseMapper.selectPage(userPage,null);
    }
}
